package org.karelun.gef.commands;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.gef.ui.actions.Clipboard;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.karelun.gef.model.Node;
import org.karelun.gef.parts.NodePart;


public class CopyNodeCommand extends AbstractCommand{
	
	private List<Node> copyList=null;
	
	@SuppressWarnings("unchecked")
	public CopyNodeCommand(ISelection selection){
		if(selection instanceof IStructuredSelection){
			IStructuredSelection s=(IStructuredSelection)selection;
			Iterator<?> itera = s.iterator();
			while(itera.hasNext()){
				Object next = itera.next();
				if(next instanceof NodePart){
					Node node=(Node)((NodePart)next).getModel();
					addCopyList(node);
				}
			}
		}
	}

	private void addCopyList(Node node) {
		if(copyList==null)
			copyList=new ArrayList<Node>();
		if(copyList.contains(node))
			return;
		copyList.add(node);
	}
	
	@Override
	public boolean canExecute() {
		if(copyList==null||copyList.isEmpty())
			return false;
		return true;
	}

	public void execute() {
		if(!canExecute())
			return;
		Clipboard.getDefault().setContents(copyList);
	}
	@Override
	public boolean canUndo() {
		return false;
	}

	@Override
	public void redo() {
		execute();
	}
	
}
